package com.dom4j;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.dl.DL;
//读写消费金额.xml的类
public class JE extends SJH{
	static Document document = null;
	public static Element root = null;
	static {
		SAXReader reader = new SAXReader();
		try {
			document = reader.read("消费金额.xml");
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		root = document.getRootElement();

	}
//保存信息
	private static void sava() {
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = null;
		try {
			writer = new XMLWriter(new FileWriter("消费金额.xml"), format);
			writer.write(document);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
//添加信息
	public static void add(String str) {
		Element element = root.addElement("手机号");
		element.addAttribute("num", str);
		Element cElement1 = element.addElement("通话时间");

		Element cElement2 = element.addElement("上网流量");

		Element cElement3 = element.addElement("短信条数");
		Element cElement4 = element.addElement("消费金额");
		sava();
	}
	//删除信息
	public  static void sc(String str){
		Iterator it =root.elementIterator();
		while(it.hasNext()){
			Element element=(Element)it.next();
			if(element.attributeValue("num").equals(str)){
				element.getParent().remove(element);
			}
		}
		sava();
	}
	//消费的具体信息写入到xml里面
	public static void xf(long num, String name, String name1, long b) {
		Iterator it = root.elementIterator();
		while (it.hasNext()) {
			Element element = (Element) it.next();
			Element celement = null;
			if (DL.num.equals(element.attributeValue("num"))) {
				if (b > 0) {
					celement = element.element(name);
					String str =celement.getText();
					if (!str.equals("")) {
						int cd=str.length()-name1.length();
						 str = celement.getText().substring(0,cd);
						num = Long.valueOf(str) + num;
					}
					str = String.valueOf(num)+name1;
					celement.setText(str);
				} else {
					celement = element.element("消费金额");
					String str = celement.getText();
					if (!str.equals("")) {
						int cd=str.length()-1;
						 str = celement.getText().substring(0,cd);
						num = Long.valueOf(str) + num;
					}
					str = String.valueOf(num + "元");
					celement.setText(str);
				}
				sava();
				break;
			}
		}
	}
}
